package kr.saeildamil.androidforstudy2.ch2930;

import kr.saeildamil.androidforstudy2.R;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.View;
import android.view.View.OnClickListener;

public class MessengerServiceTest extends Activity implements OnClickListener {
	Messenger mService;
	boolean mBound;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch29_messengerservice);
		findViewById(R.id.ch29_messengerservice_callbtn).setOnClickListener(
				this);

	}

	@Override
	public void onClick(View v) {
		if (!mBound) return;
			Message msg = Message.obtain(null, 0, 0);
		try {
			mService.send(msg);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (mBound == true) {
			unbindService(mConnection);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		bindService(new Intent(this, MessengerService.class), mConnection,
				Context.BIND_AUTO_CREATE);
	}

	ServiceConnection mConnection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			mService = null;
			mBound = false;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mService = new Messenger(service);
			mBound = true;
		}
	};

}
